﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using QD.Snapshot.Core.Util;
using System.Threading;

namespace QD.Snapshot.Core.Form
{
    public class FormBase : System.Windows.Forms.Form
    {
        protected void Echo(TextBox textbox, string msg)
        {
            EchoHelper.ShowMessage(textbox, msg);
        }

        protected void Log(string filename, string msg)
        {
            Pigeon.Utility.Log.Write(string.Format("{0}_{1}.log", filename, DateTime.Now.ToString("yyyyMMdd")), msg);
        }

        protected void AbortThread(List<Thread> listThread)
        {
            foreach (var item in listThread)
            {
                if (item.ThreadState != ThreadState.Aborted)
                    item.Abort();
            }
        }


        #region wanghui  2013-04-11 add 异常捕获
        protected void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            MessageBox.Show(str, "线程闪退", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Pigeon.Utility.Log.Error("UI线程闪退", str);
        }

        protected void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            MessageBox.Show(str, "非UI线程异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Pigeon.Utility.Log.Error("UI线程闪退", str);
        }


        /// <summary> 
        /// 生成自定义异常消息 
        /// </summary> 
        /// <param name="ex">异常对象</param> 
        /// <param name="backStr">备用异常消息：当ex为null时有效</param> 
        /// <returns>异常字符串文本</returns> 
        protected string GetExceptionMsg(Exception ex, string backStr)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);
                sb.AppendLine("【异常错误】：" + ex.ToString());
            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }
        #endregion
    }
}